#include "Searcher.h"


#ifndef BUFFER_MAXLENGTH
#define BUFFER_MAXLENGTH 4096
#endif



Searcher::Searcher(wxString query)
	{
		SearchQuery = query;
	}

bool Searcher::SetQuery(wxString query)
	{
	SearchQuery = query;
	
	if(SearchQuery == query){
		return true;
		}
	else{
		return false;
		}
	
	}

//***************************************************************************

wxString Searcher::SearchForVideos()
	{
	if(!SearchQuery)
		{
		return wxT("NULL");
		}
	
	wxString filename(wxT("SearchRes.xml"));
	//make the url that we will send to youtube
	RequestUrl = wxT("http://gdata.youtube.com/feeds/api/videos?vq="+ SearchQuery )+wxT( "&orderby=relevance");

	if(RequestUrl.GetError() == wxURL_NOERR)
		{

		wxFile TempResults( filename,wxFile::write );
		if(TempResults.IsOpened() == false) wxMessageBox(wxT("Error creating file"));
		
		wxInputStream* InStream = RequestUrl.GetInputStream();

		if(!InStream) wxMessageBox(wxT("Error creating input stream.  Check internet connection and try again."));


		//this is the part that actually downloads it
		unsigned char buffer[BUFFER_MAXLENGTH];

	do
		{
			InStream->Read(buffer,BUFFER_MAXLENGTH);
			size_t bytesread = InStream->LastRead();

			if(bytesread>0) TempResults.Write(buffer,bytesread);
		
		}while( !InStream->Eof() );
	
		//clean up a bit
		delete InStream;
		
		TempResults.Close();
		SavedSearchName = filename;
		SearchComplete = true;
		
		return filename;

		}	//if(SearchQuery == wxURL_NOERR)
	else{
		SearchComplete = false;
		return wxT("Error");
		
		}

	}
	//*********************************************

	
	wxString Searcher::SearchForVideos(wxString filename)
	{
	if(!SearchQuery)
		{
		return wxT("NULL");
		}
	
	
	//make the url that we will send to youtube
	RequestUrl = wxT("http://gdata.youtube.com/feeds/api/videos?vq="+ SearchQuery )+wxT( "&orderby=relevance");

	if(RequestUrl.GetError() == wxURL_NOERR)
		{

		wxFile TempResults( filename,wxFile::write );
		if(TempResults.IsOpened() == false) wxMessageBox(wxT("Error creating file"));
		
		wxInputStream* InStream = RequestUrl.GetInputStream();

		if(!InStream) wxMessageBox(wxT("Error creating input stream"));


		//this is the part that actually downloads it
		unsigned char buffer[BUFFER_MAXLENGTH];

		
	do
		{
			InStream->Read(buffer,BUFFER_MAXLENGTH);
			size_t bytesread = InStream->LastRead();

			if(bytesread>0) TempResults.Write(buffer,bytesread);
		}while( !InStream->Eof() );
	
		//clean up a bit
		delete InStream;
		
		TempResults.Close();
		
		SearchComplete = true;
		SavedSearchName = filename;
		return filename;

		}	//if(SearchQuery == wxURL_NOERR)
	else
		{
		SearchComplete = false;

		return wxT("Error");
		}
}


c_Videos Searcher::GetAllVideoInformation()
	{
		
	


		if(SearchComplete == true)
		{
			if(!Results.Load(SavedSearchName))
				{
				ReturnInfo.Title.Add(wxT("Couldn't Load Search Results"));
				return ReturnInfo;
				}
			//start the processing of the xml file

			if(Results.GetRoot()->GetName() != wxT("feed"))
				{
				ReturnInfo.Title.Add(wxT("Couldn't get root Node"));
				return ReturnInfo;
				}
			
			wxXmlNode *child = Results.GetRoot()->GetChildren();



				while(child)
				{
					//iterate through each video entry
				if(child->GetName() == wxT("entry"))
					{
					
					//initialize a counter to get the 4th thumbnail
					int thumbcounter = 0;

					wxXmlNode *subchildren = child->GetChildren();
					while(subchildren)
						{
						//test for title____________________________________________________
							if(subchildren->GetName() == wxT("title"))
								{
								ReturnInfo.Title.Add(subchildren->GetNodeContent());
								}
						//test for description
							// tag of type <content type="text">__________________________________
							if(subchildren->GetName() == wxT("content"))
								{
								
								wxString prop = subchildren->GetPropVal(wxT("type"),wxT("default"));
									if(prop == wxT("text"))
									{
									ReturnInfo.Description.Add(subchildren->GetNodeContent());
									}
								}
							//test for the link to the video________________________________
						if(subchildren->GetName() == wxT("link"))
							{
							wxString prop = subchildren->GetPropVal(wxT("rel"),wxT("default"));
							if(prop == wxT("alternate"))
								{
								wxString p_url = subchildren->GetPropVal(wxT("href"),wxT("default"));
								ReturnInfo.Url.Add(p_url);
								}
							}
					
						//get the author______________________________________
						if(subchildren->GetName() == wxT("author"))
							{
							wxXmlNode* authorsubnode = subchildren->GetChildren();
							while(authorsubnode)
								{
								if(authorsubnode->GetName() == wxT("name"))
									{
									ReturnInfo.Author.Add(authorsubnode->GetNodeContent());
									}
								authorsubnode = authorsubnode->GetNext();
								}
							}
							//___________________________________________________
						//branch to the "media:group" subnode
						if(subchildren->GetName() == wxT("media:group"))
							{
								wxXmlNode* mediasubnode = subchildren->GetChildren();
									while(mediasubnode)
										{
										
										//Duration.....................................
										if(mediasubnode->GetName() == wxT("yt:duration"))
											{
											long dur;
											
											wxString temp;
											temp = mediasubnode->GetPropVal(wxT("seconds"),wxT("default"));
											temp.ToLong(&dur,10);
											if(dur)
												{
											ReturnInfo.LengthInSeconds.push_back( static_cast<int> (dur) );
												}
								
											}
										//Thumbnails........................................
										if(mediasubnode->GetName() == wxT("media:thumbnail"))
											{
												thumbcounter++;
												if(thumbcounter >= 4){
													
													ReturnInfo.ThumbnailUrl.Add(mediasubnode->GetPropVal(wxT("url"),
														wxT("default")) );
													}

										


											}

										//Views........................................
										if(mediasubnode->GetName() == wxT("yt:statistics"))
											{
												long views;
												wxString temp = mediasubnode->GetPropVal(wxT("viewCount"),wxT("default"));
												temp.ToLong(&views,10);
												if(views)
													{
													ReturnInfo.Views.push_back(static_cast<int> (views));
													}
											}

										//Rating.........................................
										if(mediasubnode->GetName() == wxT("gd:rating"))
											{
											long rating;
											wxString temp = mediasubnode->GetPropVal(wxT("average"),wxT("default"));
											temp.ToLong(&rating,10);
											if(rating)
												{
												ReturnInfo.Rating.push_back(static_cast<int>(rating));
												}
											}
										mediasubnode = mediasubnode->GetNext();
										}
							}



							
							subchildren = subchildren->GetNext();
							}
					}
				child = child->GetNext();
				}
		}
	else
		{
		ReturnInfo.Title.Add(wxT("The Search is not complete"));
		return ReturnInfo;
		}

	return ReturnInfo;
	}


	c_Videos Searcher::AddAuthorsToTitles()
		{
		int titlecount;
		wxString temp;
		titlecount = static_cast<int>( ReturnInfo.Title.GetCount() );

		for(int i = 0;i<=titlecount-1;i++)
			{
			temp = ReturnInfo.Title.Item(i);
			temp.Append(wxT(" - ")+ReturnInfo.Author.Item(i));
			ReturnInfo.Title.Item(i) = temp;
			}
		return ReturnInfo;
		}

	c_Videos Searcher::ReturnVideoInformation()
		{

		return ReturnInfo;
		}



			